<template>
  <div class="feedback"> 
    <el-drawer v-model="drawer" title="反馈建议">
      <template #header>
        <h4>感谢您的反馈^_^</h4>
      </template>
      <template #default>
        <el-form :model="state.feedbackForm" :rules="state.rules" ref="feedbackRef" label-width="100px" class="questionForm">         
          <el-form-item label="内容：" prop="content">
            <el-input
                v-model="state.feedbackForm.content"
                :autosize="{ minRows: 3, maxRows: 10}"
                type="textarea"
                placeholder="请输入反馈内容"
                clearable
                />
            </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="warning" @click="drawer=false">取消</el-button>
          <el-button type="primary" @click="submitFeedbackFormClick">提交</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
  <div>
    <el-drawer v-model="state.drawer_uploadfile" title="PDF转word" size="45%">
      <template #header>
        <h4>上传pdf文件</h4>
      </template>
      <template #default>
        <UploadPdfFile :limit="state.limit" :action="state.pdf2FileServer" :father_method="handleConvertResult" 
        :file_type=state.return_file_type 
        v-loading="state.loading"/>
        <el-radio-group v-model="state.return_file_type">     
            <el-radio label="docx" >docx</el-radio>
            <el-radio label="md">latex</el-radio>
            <el-radio label="tex">tex</el-radio>
          </el-radio-group>
        <!-- <el-button v-show="state.showGetFileButton" type="success" @click="getDocxClick">点击获取docx文件</el-button>         -->
      </template>
      
      <template #footer>
        <div style="flex: auto">
          <el-button type="warning" @click="state.drawer_uploadfile=false">取消</el-button>                  
          
        </div> 
      </template>

    </el-drawer>
  </div>
  <div class="header"> 
      <div class="logo">
        <img src="../assets/logo.png" alt="logo" style="width: 40px;">
        <span>数学组卷系统</span> 
      </div>
    <!-- <div class="search"> 
      <el-input v-model="input" placeholder="" />
      <el-button type="primary" :icon="Search" @click="GetQuestionListByKeyWordSearch()"></el-button> 
    </div> -->

    <div class="right">        
      <el-menu
        class="el-menu-demo"
        mode="horizontal"
        :ellipsis="false"
        :router="true"
        active-color = #409EFF
      >
        <el-menu-item index="/">首页</el-menu-item>
        <el-menu-item index="/getQuestionsByCourse?id=1">章节组卷</el-menu-item>            
        <div class="flex-grow" />
        <el-menu-item index="/getQuestionsByPaper">联考组卷</el-menu-item>
        <el-menu-item index="/getPaper">找试卷</el-menu-item>
        <!-- <el-menu-item index="#">
          <el-tooltip content="待开发" placement="bottom" effect="dark">
            智能组卷
          </el-tooltip>
        </el-menu-item> -->
        <!-- <el-menu-item index="/getQuestionsByGenaralPaper">原创题组卷</el-menu-item> -->
        <el-menu-item index="/getGuidePapersByKnowledgepoint">导学案</el-menu-item>
        <el-sub-menu index="1">
          <template #title>录入</template>
          <el-menu-item index="/addPaperByFileStepOne?importQuestionType=ai_cut">ai切题</el-menu-item>
          <!-- <el-menu-item index="/addQuestionNoDialoge">录入单题</el-menu-item> -->
          <el-menu-item index="/addPaperByFileStepOne?importQuestionType=importQuestionsAndPaper&subject=senior&is_answer_detach=false">docx/markdown/tex导入试卷(答案附题后)</el-menu-item>
          <el-menu-item index="/addPaperByFileStepOne?importQuestionType=importQuestionsAndPaper&subject=senior&is_answer_detach=true">docx/markdown/tex导入试卷(答案试题分离)</el-menu-item>
          <el-menu-item index="/addGuidePaper">上传导学案/课件</el-menu-item>
          <el-menu-item index="/addVideoStepOne">上传微视频</el-menu-item>
          <el-menu-item index=""><el-button @click="instruction()" text>查看说明书</el-button></el-menu-item>
        
        </el-sub-menu>
        <el-sub-menu index="2">
          <template #title>ai体验馆</template>
          <el-menu-item index="/tex2pdf">tex转pdf</el-menu-item>
          <el-menu-item index="/pdf2latex">pdf转md/tex/docx</el-menu-item>
          <el-menu-item index="/handingWriteOCR">手写数学公式识别</el-menu-item>
          <!-- <el-menu-item index=""><el-button @click="pdf2wordClick()" text>pdf转word</el-button></el-menu-item>-->
          <!-- <el-menu-item index="/faceRecognition">人脸识别与分析</el-menu-item> -->
          <el-menu-item index="/chatCompletion">文生文ai</el-menu-item>
        </el-sub-menu>
        <el-sub-menu v-if="state.isLogin" index="3">
          <template #title>{{state.user_name}}</template>
          <el-menu-item index="/userCenter/addNode">私人题库</el-menu-item>
          <el-menu-item index="/userCenter/userInformation">基本资料</el-menu-item>
          <el-menu-item index="/userCenter/changePassword">修改密码</el-menu-item>
          <el-menu-item index="/userCenter/myBankPoint">库币管理</el-menu-item>
          <el-menu-item index="/userCenter/notification">通知</el-menu-item>
          <div v-if="state.isAdmin" >
            <el-sub-menu index="/adminCenter">
              <template #title>审核</template>
              <el-menu-item index="/adminCenter">首页</el-menu-item>
              <el-menu-item index="/adminCenter/withdrawLogManage">提现审核</el-menu-item>
              <el-menu-item index="/adminCenter/rechargeLogManage">充值审核</el-menu-item>
              <el-menu-item index="/adminCenter/activateAccountManage">会员审核</el-menu-item>
              <el-menu-item index="/adminCenter/jointPaperManage">试卷上线审核</el-menu-item>
              <!-- <el-menu-item index="/adminCenter/notPaperQuestionManage">题目上线审核</el-menu-item> -->
              <el-menu-item index="/adminCenter/notPaperQuestionManage">试题（公共）上线审核</el-menu-item>
              <el-menu-item index="/adminCenter/questionPrivateManage">试题（私人）上线审核</el-menu-item>
              <el-menu-item index="/adminCenter/guidePaperManage">导学案/课件上线审核</el-menu-item>
              <el-menu-item index="/adminCenter/feedbackManage">反馈管理</el-menu-item>           
            </el-sub-menu>
          </div>
          <el-sub-menu index="/userCenter/myCreatePaper">
            <template #title>试题（卷）管理</template>
            <!-- <el-menu-item index="/userCenter/myFavoriteQuestions">收藏的题目</el-menu-item> -->
            <!-- <el-menu-item index="/userCenter/myFavoritePapers" disabled>收藏的试卷</el-menu-item> -->
            <el-menu-item index="/userCenter/myCreatePaper">录入的试卷</el-menu-item>
            <el-menu-item index="/userCenter/myCreateQuestion">录入的题目</el-menu-item>
          </el-sub-menu>      
          <el-menu-item index="/userCenter/myCreateGuidePaper">导学案/课件管理</el-menu-item>
          <el-menu-item index=""><el-button @click="logoutClick" text>退出</el-button></el-menu-item> 
        </el-sub-menu>
        <el-sub-menu index="3" v-else>
          <template #title><el-button text>登录</el-button></template>
          <el-menu-item index="/login">先登录哦^_^</el-menu-item>
        </el-sub-menu>
        <!-- <el-sub-menu index="4">
          <template #title><el-button text>疯狂刷题</el-button></template>
          <el-menu-item index="/puzzle/accordingToKnowledge">按知识点</el-menu-item>
          <el-menu-item index="/puzzle/accordingToExaminationPaper">按试卷</el-menu-item>
          <el-menu-item index=""><el-button @click="accordingToExaminationPaperClick" text>按知识点</el-button></el-menu-item>
          <el-menu-item index=""><el-button @click="timeLimitClick" text>限时训练</el-button></el-menu-item>
          <el-menu-item index="/puzzle/wrongQuestionSets">错题集</el-menu-item>
        </el-sub-menu> -->
        <el-sub-menu index="5">
          <template #title><el-button text>联系我们</el-button></template>
          <el-menu-item index=""><el-button @click="conCactUsClick()" text>联系我们</el-button></el-menu-item>
          <el-menu-item index=""><el-button @click="drawer = true" text>反馈意见</el-button></el-menu-item>
          <el-menu-item index="/userCenter/frequentQuestions">常见问答</el-menu-item>
        </el-sub-menu>
      </el-menu>   
    </div>
    <div>
      <el-dialog
        v-model="state.contactUsDialogVisible"
        title="联系我们"
        width="40%"       
      >
      <div class="contactUs">
        <div class="contactUsLeft">
          <h1>联系人：朱老师</h1>
          <h1>地址：高中信息技术题库联盟</h1>
        </div>
        <div class="contactUsRight">
          <img src="@/assets/weixin_icon.jpg" alt="微信号：juhagen" />
          <img src="@/assets/douyin_icon.jpg" alt="抖音号：有理叔" />          
        </div>
      </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="state.contactUsDialogVisible = false">关闭</el-button>            
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {onMounted,  reactive, ref, h, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { localRemove, pathMap, localGet, localSet } from '@/utils'
import { Search, Document } from '@element-plus/icons-vue'
import axios from '@/utils/axios' 
import { ElMessage, ElNotification } from 'element-plus'
import { pdf2wordServer, pdf2FileServer } from '@/utils'
import UploadPdfFile from '@/components/UploadPdfFile.vue'


const url_weixin="@/assets/douyin.jpg"
const url_douyin="@/assets/douyin.jpg"
const conCactUsClick = () => {
  state.contactUsDialogVisible=true;
  // ElNotification({
  //   icon: ContactMeIcon,
  //   title: '联系我们',
  //   dangerouslyUseHTMLString: true,
  //   message: h('div',{id:'contact'},[
  //     h('p',null,'联系人：朱老师'),
  //     h('p',null,'地址：高中技术题库联盟'),      
  //     h('img',{src:url_douyin,alt:'抖音号：有理叔'}),
  //     h('img',{src:url_weixin,alt:'微信号:juhagen'})  
  //   ]),
  
  //   position: 'top-left',
  // })
}
const emit=defineEmits(['submit'])
const handleSubmitButton=()=>{
  //通知组件上的自定义submit事件执行
  emit('submit')
}
const router = useRouter()
const route = useRoute
const input = ref('')
const state = reactive({
  loading: false,
  return_file_type: 'docx',
  notifications: [],
  drawer_uploadfile: false,
  showGetFileButton: false,
  loading:false,
  count: '',
  timer: null,
  docx_token:'',
  status:0,
  name: '首页',
  isLogin: false,
  isAdmin: false,
  user_name: Object,
  rules: { // 规则
    content: [
      {required: 'true', message: '请填写反馈内容', trigger: ['change']}
    ],
  },
  feedbackForm: {
    content: "请输入反馈内容",  
  },
  pdf2wordServer,
  pdf2FileServer,
})
const drawer = ref(false)
const feedbackRef = ref(null)

onMounted(() => {
  state.name = pathMap[route.name]
  if(localGet('isLogin')){
    let user = localGet('user_information')
    // console.log("用户信息：", user)
    // console.log("user.is_staff:", user.is_staff)
    state.user_name = user.real_name
    state.isLogin = true
    if(user.is_staff ===true || user.is_supperuser === true){
      state.isAdmin = true
      // console.log("已经设置isAdmin", state.isAdmin)
    }
  }
})
router.afterEach((to) => {
  state.name = pathMap[to.name]
})
const GetQuestionListByKeyWordSearch =()=>{
  ElNotification({
    title: '搜索题目',    
    message: '下个版本一定实现搜题功能哦，敬请关注',
    type: 'warning',
    position: 'top-right',
  })
}
//退出登陆
const logoutClick=()=>{
  localRemove('token')
  localRemove('user_information')
  localRemove('isLogin')
  state.isLogin = false
  state.isAdmin = false
  router.push('/login')
}
// 提交反馈表单给后台
const submitFeedbackFormClick=()=>{
    feedbackRef.value.validate((vaild, obj) => {
    if (vaild) {
      console.log("表单验证成功，我要发送帮助反馈啦：")        
      // 持久化到数据库中,并把<br>符号转换回\n，发给后端
      var re = /<br>/g
      let params = {            
        content: state.feedbackForm.content.replace(re, "\n"),    
      }     
      axios.post(`/FeedbackViewSet/`,params).then(res =>{
        if (res.code == 200){
          ElMessage.success("恭喜你，反馈成功啦，感谢您的反馈")
        }else{
          ElMessage("很遗憾，反馈失败！")
          console.log("反馈失败：", res)
        }
      }) 
      drawer.value = false
    }else{
      ElMessage("表单没有完成！")
      console.log("表单没有通过！",obj)       
      for (let key in obj) {
        console.log("具体原因：", obj[key][0].message)
        return false;
      }
    }
  })
}
// 录入试题和试卷说明书
const instruction=()=>{
  ElNotification({
    title: '录入说明',
    dangerouslyUseHTMLString: true,
    message: '<b>录入单题</b>：就是只录入单个题目，<b>该试题记录在章节组卷栏目</b>，不记录到试卷组卷栏目<br>' +
      '<b>导入试题</b>：以word形式导入多个题目，<b>该试题记录在章节组卷栏目</b>，不记录到试卷组卷栏目<br>'+
      '<b>导入试卷</b>：以word形式导入多个题目，该试题记录在章节组卷栏目，<b>也记录到试卷组卷栏目</b><br>',
    type: 'success',
    position: 'top-right',
  })
}
// 提交pdf按钮事件
const pdf2wordClick=()=>{
  state.drawer_uploadfile=true
}
//倒计时60秒
//const countDown=()=>{
    // const TIME_COUNT = 15;
  //   if(!state.timer){
  //     state.count =TIME_COUNT;
  //     state.showGetPhoneCodeButton = false;
  //     state.timer = setInterval(()=>{
  //       if(state.count>0 && state.count<=TIME_COUNT){
  //         state.count--;
  //       }else{
  //         state.showGetPhoneCodeButton = true;
  //         clearInterval(state.timer);
  //         state.timer = null;
  //       }
  //     },1000)
  //   }
  // }
// 处理后端发送pdf后
const handleConvertResult= (code, res)=>{
  console.log('code:', code)
  console.log('后端发来文件：', res)
  state.loading = true
  if(code==1){
    state.loading=false  
    if(res.code==500){
        ElMessage.error("服务器故障，请联系管理员")
    }else
    if(res.code==200){
        ElMessage.success("docx文件已经到达，请及时下载文件")
        let url = res.data.results
        const link = document.createElement('a');
        link.href = url;
        if(state.return_file_type=='docx'){
          link.setAttribute('download', 'download.docx')
        }          
        else{
          link.setAttribute('download', 'download.zip')
        }
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link)
    }else{
      // ElMessage.error("上传失败")
      console.log("上传失败")
    }
  }
}
// 手动获取下载docx文件，携带token
const getDocxClick=()=>{
  let params = { docx_token: state.docx_token }
  axios.get('/Pdf2DocxAPIView/', {params}).then(res => {
    console.log("后端发过来了,",res)
    if(res.code==200){ 
        ElMessage.success("docx文件已经到达，请及时下载文件")
        let url = res.data.results
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'download.docx');
        // link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link)
    }else
    if(res.code==201){
        ElMessage.error("文件正在转换ing,5秒后再试试")       
    }else{
      ElMessage.error("文件下载失败，请重新上传pdf")
    }     
  })
  .catch((error)=>{
    console.log("手工下载docx文件错误",error)
      state.showGetFileButton = false;
      ElMessage.error("服务器故障，请联系管理员")
  })
}

// 图片转word文件单击事件处理
const image2wordClick=()=>{
  console.log("打开抽屉")
}
// 人脸识别与分析
const faceRecognitionClick=()=>{
  router.push('faceRecognition')
}
// 获取后台通知
const getNotification=()=>{
  axios.get('/NotificationModelViewSet/only_owner').then(res => {
    console.log("后端发来通知了：",res)
    if(res.code==200){ 
        console.log("接收通知成功")
        state.notifications = res.data.results
    }else{
      ElMessage.error("读取系统通知失败！")
    }
  })
  .catch((error)=>{
    console.log("读取系统通知错误",error)     
  })
}
let hasNotReadNotificationCount = computed({
        //get方法返回值
        get:()=>{
            return state.notifications.filter((v)=>{
              return v.status == 1
            })
        },
        //set方法设置值
        set:(val)=>{
            console.log("set方法未定义")
        }
    })

// 限时训练按钮被点击
const timeLimitClick=()=>{
  ElNotification({
    title: '限时训练',
    message: h('i', { style: 'color: teal' }, '开发中，敬请期待'),
    type: 'warning',
  })
}
// 按知识点按钮被点击事件
const accordingToExaminationPaperClick=()=>{
  ElNotification({
    title: '按知识点刷题',
    message: h('i', { style: 'color: teal' }, '开发中，敬请期待'),
    type: 'warning',
  })
}
</script>

<style scoped>
  .header {
    height: 40px;
    /* border-radius: 10px 50% 50% 40px; */
    /* border-bottom: 1px solid #666666; */
    box-shadow: 0px 0px 1px 0px rgba(88, 85, 85, 0.8);
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;
    padding: 1px auto;
    margin: 1px;
    width: 1180px!important;
  }
  .right {
    display: flex;
    flex-flow: row nowrap;
    justify-items: flex-end;
    height: 40px;
    font-size: 12px;
    font-family: 'Times New Roman', '微软雅黑';
    font-weight: bold;
  }
  .flex-grow {
    flex-grow: 1;
  }
  .search {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: center;
    margin: 0 auto;
    height: 40px;
  }
  .left{
    display: flex;
    flex-flow: row nowrap;
    justify-content:left;
    align-items: center;
    margin: 0 auto;
    height: 50px;
  }
  .logo{
    display: flex;
    flex-flow: row nowrap;
    justify-content:left;
    align-items: center;    
    height: 40px;
    width: 150px!important;
    background-image: linear-gradient(#3955f0, #C5D7A1);
  }
  .feedback{
    z-index: 10;
  }
  .contactUs{
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;    
  }
  .contactUsRight{
    display: flex;
    flex-flow: row nowrap;
  }
</style>